<template>
  <scroll-view class="cart-box" scroll-y @scrolltolower="handlerScroll">

    <!-- 主体内容 -->
    <view class="cart-box-content">

      <!-- 头部管理栏 -->
      <view class="cart-box-header">
        <view class="cart-box-header-left">
          <text class="cart-box-header-left-title"> 购物车</text>
          <text class="cart-box-header-left-address" @click="onMeanuChoose('地址')"> {{
            goodsStore.defaultAddress.address_id != "" ? goodsStore.defaultAddress.address_street : "地址详细信息"
          }}</text>
        </view>

        <text class="cart-box-header-manage" @click="manage = !manage"> {{ manage ? "管理" : "完成" }}</text>
      </view>

      <!-- 商品内容 -->
      <view v-if="goodsStore.shoppingCart.length > 0" style="width: 98%; padding:0 20rpx;"
        v-for="(item, index) in goodsStore.shoppingCart" :key="item.cart_id">
        <goods-cart-list @goods-choose.stop="selectProduct" :index="index" :shoppingCart="item"
          @commodity-num.stop="commodityNum" :selected-all="allBthSwitch"></goods-cart-list>
      </view>

      <!-- 没有商品内容时显示 -->
      <view class="cart-list-none" v-else>
        <image src="/src/components/goods_cart/images/cart-none.png" mode="scaleToFill" />
        <view class="cart-list-none-title">购物车暂时没有商品</view>
        <view class="cart-list-none-subheading">您可以选择喜欢的商品加入购物车</view>
        <navigator url="/pages/" open-type="navigate" hover-class="navigator-hover" class="cart-list-none-to">
          前往选购
        </navigator>
      </view>

    </view>


    <!-- 商品推荐 -->
    <view class="cart-recommend">
      <view class="cart-recommend-title">更多推荐商品</view>
      <goods :list="goodsList" :classify="[]"></goods>
    </view>


    <!-- 底部技术支持 -->
    <view class="cart-technology"> 技术支持：不想说话而已 </view>

    <!-- 底部商品结算栏目 -->
    <view class="cart-settlement">

      <!-- 左侧全选按钮 -->
      <view class="cart-settlement-all" @click="handlerAllBth">
        <view :class="allBth ? 'cart-settlement-all-bth-choose' : 'cart-settlement-all-bth'">
        </view>
        <text>全选</text>
      </view>

      <!-- 右侧结算栏目 -->
      <view v-if="manage" class="cart-settleme-freight">
        <view>
          <view class="cart-settlement-subheading">
            <text>不含运费</text>
            <text style="font-size: 28rpx;margin: 0 10rpx;">合计:</text>
            <text class="cart-settlement-subheading-price">{{ allPrice }}</text>
          </view>
          <view>
            <text class="cart-settlement-subheading">共优惠：￥{{ allPreferential }}</text>
            <text class="cart-settlement-preferential-detail">优惠明细</text>
          </view>
        </view>
        <view class="cart-settleme-bth" @click="settlement">结算</view>
      </view>

      <!-- 右侧删除按钮 -->
      <view v-else class="cart-delete-bth" @click="cartDelete">删除</view>

    </view>

    <!-- 底部地址菜单 -->
    <goods-cart-address :address-list="addressList" @choose-address="chooseAddress" v-show="meanuChoose === '地址'"
      @shut-down="onMeanuChoose"></goods-cart-address>

  </scroll-view>
</template>

<script lang="ts" setup>
import GoodsCartAddress from "../../components/goods_cart/goods_cart_address/GoodsCartAddress.vue"
import Goods from "../../components/goods/Goods.vue"
import GoodsCartList from "../../components/goods_cart/goods_cart_list/GoodsCartList.vue"
import { ref } from "vue"
import { useGoodsStore } from "../../pinia/goods"
import type { ShoppingCart, GoodsList, DistributionAddress } from "../../config/data/data"
import { onLoad, onReady, onShow, onHide, onUnload } from '@dcloudio/uni-app';

//全局状态实例
const goodsStore = useGoodsStore();

//商品列表数据
const goodsList = ref<GoodsList[]>([]);

//配送地址列表数据
const addressList = ref<DistributionAddress[]>([]);

//监听滚动条是否触底
const handlerScroll = () => {
  //加载下一页商品列表数据
};

//底部菜单弹出选项
const meanuChoose = ref("");
//弹出菜单，关闭菜单
const onMeanuChoose = (item: string) => {
  meanuChoose.value = item;
}

//全选按钮是否开启
const allBthSwitch = ref();
//全选按钮
const allBth = ref(false);
//全选事件
const handlerAllBth = () => {
  allBth.value = !allBth.value
  allBthSwitch.value = allBth.value;
  selectProductList.value = [];
  selectProductListIndex.value = [];
  if (allBth.value) {
    selectProductList.value = goodsStore.shoppingCart.filter(item => item.cart_id != '');
    selectProductList.value.forEach((value, index) => {
      selectProductListIndex.value.push(index);
    })
  }
  allPrice.value = selectProductList.value.reduce((num, item) => {
    let price = item.cart_discount > 0.00 ? item.cart_discount : item.cart_price
    return Number((num + price).toFixed(2))
  }, 0)
  allPreferential.value = selectProductList.value.reduce((num, item) => {
    let price = item.cart_discount > 0.00 ? item.cart_price - item.cart_discount : 0
    return Number((num + price).toFixed(2))
  }, 0)
}

//选中的商品集合
const selectProductList = ref<ShoppingCart[]>([]);
//选中的商品的下标
const selectProductListIndex = ref<number[]>([]);
//选中商品事件
const selectProduct = (shoppingCart: ShoppingCart, index: number) => {

  allBthSwitch.value = null;
  const indexOf = selectProductListIndex.value.findIndex(item => item === index);
  if (indexOf != -1) {
    selectProductList.value.splice(indexOf, 1);
    selectProductListIndex.value.splice(indexOf, 1);
  } else {
    selectProductList.value.push(shoppingCart)
    selectProductListIndex.value.push(index)
  }
  if (selectProductList.value.length === goodsStore.shoppingCart.length) {
    allBth.value = true
  } else {
    allBth.value = false
  }
  allPrice.value = selectProductList.value.reduce((num, item) => {
    let price = item.cart_discount > 0.00 ? item.cart_discount : item.cart_price
    return Number((num + price).toFixed(2))
  }, 0)

  allPreferential.value = selectProductList.value.reduce((num, item) => {
    let price = item.cart_discount > 0.00 ? item.cart_price - item.cart_discount : 0
    return Number((num + price).toFixed(2))
  }, 0)
}

//商品数量增减
const commodityNum = (index: number, bool: boolean) => {
  if (bool) {
    if (goodsStore.shoppingCart[index].cart_num === 99) {
      uni.showToast({
        title: '最多一次性可购买99件商品', // 提示内容
        duration: 1000, // 显示时长，默认为2秒，可传入数字，单位毫秒
        icon: 'none' // 不显示图标（可选值有'success', 'loading', 'none'）
      })
    } else {
      goodsStore.shoppingCart[index].cart_num += 1;
    }


  } else {
    if (goodsStore.shoppingCart[index].cart_num === 1) {
      uni.showToast({
        title: '最少购买一件商品', // 提示内容
        duration: 1000, // 显示时长，默认为2秒，可传入数字，单位毫秒
        icon: 'none' // 不显示图标（可选值有'success', 'loading', 'none'）
      })
    } else {
      goodsStore.shoppingCart[index].cart_num -= 1;
    }

  }

}

//购物车删除商品
const cartDelete = () => {
  uni.showModal({
    title: '确认删除？', // 提示标题
    content: '确定删除这' + selectProductList.value.length + '件商品吗？', // 提示内容
    showCancel: true, // 显示取消按钮，默认为true
    cancelText: '取消', // 取消按钮的文字，默认为"取消"
    confirmText: '确认', // 确认按钮的文字，默认为"确定"
    success: function (res) {
      if (res.confirm) {
        if (allBth.value) {
          goodsStore.shoppingCart = [];
          selectProductList.value = [];
          allBth.value = false;
          allBthSwitch.value = null;
          return;
        }
        selectProductListIndex.value.sort((a, b) => b - a);
        for (let i of selectProductListIndex.value) {
          goodsStore.shoppingCart.splice(i, 1)
        }
        selectProductListIndex.value = [];
        selectProductList.value = [];

        uni.showToast({
          title: '删除成功', // 提示内容
          duration: 1000, // 显示时长，默认为2秒，可传入数字，单位毫秒
          icon: 'none' // 不显示图标（可选值有'success', 'loading', 'none'）
        })
      } else if (res.cancel) {
        uni.showToast({
          title: '取消删除', // 提示内容
          duration: 1000, // 显示时长，默认为2秒，可传入数字，单位毫秒
          icon: 'none' // 不显示图标（可选值有'success', 'loading', 'none'）
        })
      }
    }
  });
}

//购物车商品结算
const settlement = () => {
  console.log("商品结算", selectProductList.value)
}

//是否进入管理
const manage = ref(true);

//商品的总价格
const allPrice = ref(0.00);

//商品共优惠
const allPreferential = ref(0.00);

//监听当前选中地址事件
const chooseAddress = (item: DistributionAddress) => {
  goodsStore.defaultAddress = item;
}

onLoad(() => {
  //商品列表数据
  goodsList.value = [
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1032",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护【精美的】",
      commodity_inventory: 123
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1031",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 243
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1030",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 23
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1029",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 23
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1028",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 12
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1027",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 20
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1026",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 2
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1025",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 12
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1024",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 56
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1023",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 34
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1022",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 34
    },
    {
      commodity_image: 'https://www.lyzhnb.top/wf/wf-.jpg',
      commodity_id: "1021",
      commodity_price: 28.8,
      commodity_discount: 22.8,
      commodity_msg: "精美的肌肤需要您的精心呵护",
      commodity_inventory: 343
    }
  ];


  //配送地址数据列表
  addressList.value = [{
    address_id: "12321",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "长春村老园队对018号", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12331",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "长春村老园队对018号", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12431",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "长春村老园队对018号", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12351",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "宁潭镇", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12631",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "宁潭镇", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12731",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "宁潭镇", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12381",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "宁潭镇", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }, {
    address_id: "12391",
    address_city: "玉林市",
    address_province: "广西",
    address_county: "博白县",
    address_town: "宁潭镇", //配送镇
    address_street: "宁潭镇", //配送地址街道
    address_username: "李某某", //收货人
    address_phone: "123132131"
  }]

})
// 页面周期函数--监听页面初次渲染完成
onReady(() => {

});
// 页面周期函数--监听页面显示(not-nvue)
onShow(() => {

});
// 页面周期函数--监听页面隐藏
onHide(() => {
  allBth.value = true;
  handlerAllBth();
  manage.value = true;
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0 // 立即滚动到顶部
  })
});
// 页面周期函数--监听页面卸载
onUnload(() => {

});
// 页面处理函数--监听用户下拉动作
// onPullDownRefresh() { uni.stopPullDownRefresh(); },
// 页面处理函数--监听用户上拉触底
// onReachBottom() {},
// 页面处理函数--监听页面滚动(not-nvue)
// onPageScroll(event) {},
// 页面处理函数--用户点击右上角分享
// onShareAppMessage(options) {},

</script>

<style scoped lang="scss">
.cart-box {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 这里实现的是垂直居中 */
  align-content: center;
  position: relative;
  background-color: $uni-bg-color;

  .cart-technology {
    height: 400rpx;
    width: 100%;
    line-height: 400rpx;
    text-align: center;
    font-size: 28rpx;
    color: $uni-bg-color-mask;
  }

  .cart-recommend {
    width: 100%;
    text-align: center;

    .cart-recommend-title {
      font-size: 26rpx;
      height: 60rpx;
      line-height: 60rpx;
      background-color: $uni-box-color;
    }
  }

  .cart-box-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20rpx;

    .cart-list-none {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 400rpx;
      font-size: 26rpx;

      image {
        width: 120rpx;
        height: 120rpx;
        padding: 20rpx;
      }

      .cart-list-none-subheading {
        color: $uni-bg-color-mask;
      }

      .cart-list-none-to {
        width: 200rpx;
        height: 50rpx;
        line-height: 50rpx;
        text-align: center;
        color: $uni-color-error;
        border: 2rpx solid rgb(184, 3, 3);
        border-radius: 25rpx;
        background-color: $uni-box-color;
        margin: 20rpx 0;
      }
    }

    .cart-box-body {
      position: relative;
      display: flex;
      align-items: center;
      width: 95%;
      min-height: 250rpx;
      max-height: 350rpx;
      padding: 10rpx 20rpx;
      margin: 10rpx 0;
      background-color: $uni-box-color;
      border-radius: 20rpx;



      .cart-box-body-detail {
        max-width: 400rpx;
        width: 100%;
        height: 100%;
        display: flex;
        font-size: 28rpx;
        flex-direction: column;
        justify-content: center;


        .cart-box-body-detail-title {
          min-height: 50rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .cart-box-body-detail-price {
          display: flex;
          justify-content: space-between;
          align-items: center;

        }

        .cart-box-body-detail-specification {
          position: relative;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
          overflow: hidden;
          margin: 20rpx 0;
          width: fit-content;
          color: $uni-bg-color-mask;
          text-indent: 40rpx;
          padding: 5rpx;
          border-radius: 10rpx;
          background-color: rgba(210, 208, 208, 0.354);

          &::after {
            position: absolute;
            top: 10rpx;
            left: 10rpx;
            content: "";
            display: flex;
            justify-content: center;
            align-items: center;
            width: 15rpx;
            height: 15rpx;
            border: 2rpx solid rgb(142, 141, 141);
            border-left: transparent;
            border-top: transparent;
            transform-origin: center center;
            transform: rotate(45deg);
          }
        }
      }

      .cart-box-body-bth {
        width: 25rpx;
        height: 25rpx;
        border: 2rpx solid rgb(140, 138, 138);
        border-radius: 50%;
      }

      .cart-box-body-bth-choose {
        border: 2rpx solid red;
        background-color: rgb(254, 222, 180)
      }

      image {
        width: 180rpx;
        height: 180rpx;
        border-radius: 4rpx;
        margin: 10rpx 10rpx 10rpx 20rpx;
      }

      .cart-box-body-detail-quantity {
        display: flex;
        align-items: center;

        view {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 50rpx;
          height: 50rpx;
          line-height: 50rpx;
          margin: 0 5rpx;
          background-color: rgba(232, 228, 228, 0.316);
        }
      }
    }


    .cart-box-header {
      position: sticky;
      top: 0;
      display: flex;
      width: 100%;
      height: 90rpx;
      align-items: center;
      justify-content: space-between;
      background-color: $uni-box-color;
      z-index: 9;

      .cart-box-header-left {

        .cart-box-header-left-title {
          font-weight: 600;
          margin-right: 20rpx;
        }

        .cart-box-header-left-address {
          font-size: 24rpx;
          color: $uni-bg-color-mask;

          &::after {
            content: "";
            display: inline-block;
            width: 15rpx;
            height: 15rpx;
            background-color: transparent;
            border: 2rpx solid red;
            border-left: rgba(0, 0, 0, 0);
            border-top: rgba(0, 0, 0, 0);
            transform-origin: center center;
            transform: rotateZ(45deg) translateY(-7rpx);
            margin-left: 10rpx;
          }
        }

      }

      .cart-box-header-manage {
        font-size: 26rpx;
        font-weight: 600;
      }
    }
  }



  .cart-settlement {
    position: fixed;
    bottom: 0;
    left: 50%;
    width: 100%;
    min-height: 100rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 26rpx;
    transform: translateX(-50%);
    background-color: $uni-box-color;

    .cart-delete-bth {
      width: 180rpx;
      height: 70rpx;
      text-align: center;
      line-height: 70rpx;
      color: $uni-box-color;
      background-color: red;
      border-radius: 35rpx;
      margin-right: 20rpx;
    }

    .cart-settlement-all {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 20rpx;

      .cart-settlement-all-bth,
      .cart-settlement-all-bth-choose {
        width: 25rpx;
        height: 25rpx;
        border-radius: 50%;
        border: 2rpx solid rgb(45, 45, 45);
        margin-right: 10rpx;
      }

      .cart-settlement-all-bth-choose {
        border: 2rpx solid red;
        background-color: rgb(251, 214, 150);
      }
    }

    .cart-settleme-freight {
      display: flex;
      align-items: center;
      text-align: right;
      font-size: 24rpx;
      color: $uni-bg-color-mask;
      padding: 0 20rpx;

      .cart-settlement-subheading {

        text,
        view {
          transform: all .2s;
        }

        .cart-settlement-subheading-price {
          font-size: 32rpx;
          color: red;

          &::before {
            content: "￥";
            font-size: 24rpx;
            color: red;
          }
        }
      }

      .cart-settlement-preferential-detail {
        color: rgb(14, 14, 14);
        margin: 0 8rpx;
      }

      .cart-settleme-bth {
        width: 160rpx;
        height: 65rpx;
        text-align: center;
        line-height: 65rpx;
        border-radius: 32rpx;
        background-color: red;
        color: $uni-box-color;
        margin-left: 20rpx;
      }
    }
  }
}
</style>